package com.campus.payment.controller;

import com.campus.common.bean.common.Resp;
import com.campus.common.enums.OrderStatusEnum;
import com.campus.payment.dto.*;
import com.campus.payment.feign.OrderFeignClient;
import com.campus.payment.service.WechatPayService;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.time.LocalDateTime;

/**
 * 支付控制器
 *
 * @author ZhaoYuJie
 * @since 2025-01-15
 */
@RestController
@RequestMapping("/payment")
@Api(tags = "支付管理")
@Slf4j
public class PaymentController {

    @Autowired
    private WechatPayService wechatPayService;
    
    @Autowired
    private OrderFeignClient orderFeignClient;

    @PostMapping("/createPayOrder")
    @ApiOperation("创建微信支付订单")
    public Resp<PayOrderResponseDTO> createPayOrder(@RequestBody PayOrderRequestDTO request) {
        try {
            PayOrderResponseDTO response = wechatPayService.createPayOrder(request);
            return Resp.success(response);
        } catch (Exception e) {
            log.error("创建支付订单失败", e);
            return Resp.error("创建支付订单失败: " + e.getMessage());
        }
    }

    @PostMapping("/closeOrder")
    @ApiOperation("关闭订单")
    public Resp<String> closeOrder(@RequestBody CloseOrderRequestDTO request) {
        try {
            wechatPayService.closeOrder(request);
            return Resp.success("订单关闭成功");
        } catch (Exception e) {
            log.error("关闭订单失败", e);
            return Resp.error("关闭订单失败: " + e.getMessage());
        }
    }

    @PostMapping("/queryOrderStatus")
    @ApiOperation("查询订单支付状态")
    public Resp<String> queryOrderStatus(@RequestBody OrderStatusQueryDTO request) {
        try {
            String status = wechatPayService.queryOrderStatus(request.getOutTradeNo(), request.getSubMchid());
            return Resp.success(status);
        } catch (Exception e) {
            log.error("查询订单状态失败", e);
            return Resp.error("查询订单状态失败: " + e.getMessage());
        }
    }

    @PostMapping("/queryOrderDetail")
    @ApiOperation("查询订单详情")
    public Resp<Transaction> queryOrderDetail(@RequestBody OrderStatusQueryDTO request) {
        try {
            Transaction transaction = wechatPayService.queryOrderByOutTradeNo(request);
            return Resp.success(transaction);
        } catch (Exception e) {
            log.error("查询订单详情失败", e);
            return Resp.error("查询订单详情失败: " + e.getMessage());
        }
    }

    @PostMapping("/wechatPayCallback")
    @ApiOperation("微信支付回调")
    public ResponseEntity<String> wechatPayCallback(HttpServletRequest request) {
        try {
            // 获取请求头中的签名信息
            String wechatpaySignature = request.getHeader("Wechatpay-Signature");
            String wechatpayTimestamp = request.getHeader("Wechatpay-Timestamp");
            String wechatpayNonce = request.getHeader("Wechatpay-Nonce");
            String wechatpaySerial = request.getHeader("Wechatpay-Serial");
            
            // 读取请求体
            StringBuilder requestBody = new StringBuilder();
            try (BufferedReader reader = request.getReader()) {
                String line;
                while ((line = reader.readLine()) != null) {
                    requestBody.append(line);
                }
            }
            String body = requestBody.toString();
            
            // 构造回调DTO
            PaymentCallbackDTO callbackDTO = new PaymentCallbackDTO();
            callbackDTO.setWechatpaySignature(wechatpaySignature);
            callbackDTO.setWechatpayTimestamp(wechatpayTimestamp);
            callbackDTO.setWechatpayNonce(wechatpayNonce);
            callbackDTO.setWechatpaySerial(wechatpaySerial);
            callbackDTO.setRequestBody(body);
            
            WechatPayService.PaymentCallbackResult result = wechatPayService.handlePaymentCallback(callbackDTO);
            
            if (result.isSuccess()) {
                // 调用订单服务更新订单状态
                try {
                    OrderStatusUpdateDTO updateRequest = new OrderStatusUpdateDTO();
                    updateRequest.setOrderId(result.getOutTradeNo());
                    updateRequest.setTransactionId(result.getTransactionId());
                    updateRequest.setPayTime(LocalDateTime.now());
                    updateRequest.setStatus(OrderStatusEnum.PENDING_ACCEPTANCE.getValue()); // 待接单状态
                    updateRequest.setStatusText(OrderStatusEnum.PENDING_ACCEPTANCE.getText());
                    
                    Resp<String> updateResult = orderFeignClient.updatePaymentStatus(updateRequest);
                    if ("0".equals(updateResult.getCode())) {
                        log.info("支付回调成功，订单状态更新成功，订单号：{}，微信支付订单号：{}", result.getOutTradeNo(), result.getTransactionId());
                    } else {
                        log.error("支付回调成功，但订单状态更新失败，订单号：{}，错误信息：{}", result.getOutTradeNo(), updateResult.getMessage());
                    }
                } catch (Exception e) {
                    log.error("支付回调成功，但调用订单服务更新状态失败，订单号：{}", result.getOutTradeNo(), e);
                }
                
                // 微信支付回调成功时返回HTTP 200状态码和空响应体
                return ResponseEntity.ok().build();
            } else {
                // 微信支付回调失败时返回HTTP 400状态码和指定的JSON报文
                String failResponse = "{\"code\":\"FAIL\",\"message\":\"失败\"}";
                return ResponseEntity.badRequest().body(failResponse);
            }
        } catch (Exception e) {
            log.error("微信支付回调处理异常", e);
            // 微信支付回调异常时返回HTTP 500状态码和指定的JSON报文
            String failResponse = "{\"code\":\"FAIL\",\"message\":\"失败\"}";
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(failResponse);
        }
    }
}